package com.linjiahao.nettyOne.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linjiahao.nettyOne.client.UserCenterClient;
import com.linjiahao.nettyOne.domain.ChatList;
import com.linjiahao.nettyOne.domain.ChatMessage;
import com.linjiahao.nettyOne.mapper.ChatListMapper;
import com.linjiahao.nettyOne.mapper.ChatMessageMapper;
import com.linjiahao.nettyOne.service.ChatListService;
import com.linjiahao.nettyOne.vo.ChatListVO;
import com.linjiahao.servicebase.common.BaseConstant;
import com.linjiahao.servicebase.common.ResultMap;
import com.linjiahao.servicebase.vo.NettyMessageVO;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
*
*/
@Service
public class ChatListServiceImpl extends ServiceImpl<ChatListMapper, ChatList> implements ChatListService{

    @Resource
    private ChatMessageMapper chatMessageMapper;

    @Resource
    private UserCenterClient userCenterClient;

    @Override
    public List<ChatListVO> getCurrentChatList(Long userId,Integer pageNo,Integer pageSize) {
        Page<ChatList> page = new Page(pageNo,pageSize);
        QueryWrapper<ChatList> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ChatList::getUserId,userId).eq(ChatList::getIsDelete, BaseConstant.Not_Pass)
                .select(ChatList::getFriendId,ChatList::getMessageId,ChatList::getUpdateTime).orderByDesc(ChatList::getUpdateTime);
        IPage<ChatList> iPage = this.baseMapper.selectPage(page, wrapper);
        List<ChatListVO> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(iPage.getRecords())){
            List<ChatList> records = iPage.getRecords();
            Map<Long, String> messageMap = records.stream().collect(Collectors.toMap(ChatList::getFriendId, ChatList::getMessageId, (k1, k2) -> k1));
            List<Long> friendIds = new ArrayList<>(messageMap.keySet());
            List<String> messageIds = messageMap.values().stream().collect(Collectors.toList());
            QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(ChatMessage::getMessageId,messageIds).eq(ChatMessage::getIsDelete,BaseConstant.Not_Pass)
                    .select(ChatMessage::getMessageData,ChatMessage::getMessageType,ChatMessage::getUpdateTime);
            List<ChatMessage> messageList = chatMessageMapper.selectList(queryWrapper);
            Map<String, ChatMessage> map = messageList.stream().collect(Collectors.toMap(ChatMessage::getMessageId, a -> a, (k1, k2) -> k1));
            ResultMap infoList = userCenterClient.getUserInfoList(friendIds);
            list = JSON.parseArray(JSON.toJSONString(infoList.getData().get("list")), ChatListVO.class);
            list.stream().forEach(m ->{
                String messageId = messageMap.get(m.getUserId());
                if(map.containsKey(messageId)){
                    ChatMessage chatMessage = map.get(messageId);
                    m.setMessage(chatMessage.getMessageData());
                    m.setMessageType(chatMessage.getMessageType());
                    m.setMessageTime(chatMessage.getUpdateTime());
                }
            });
        }
        return list;
    }

    @Override
    public String addChatList(NettyMessageVO nettyMessageVO) {
        ChatList one = this.baseMapper.selectOne(new QueryWrapper<ChatList>().lambda().eq(ChatList::getUserId, nettyMessageVO.getUserId())
                .eq(ChatList::getFriendId, nettyMessageVO.getReceiveId()).eq(ChatList::getIsDelete, BaseConstant.Not_Pass));
        if(one == null){
            ChatList add = new ChatList();
            add.setUserId(nettyMessageVO.getUserId());
            add.setFriendId(nettyMessageVO.getReceiveId());
            //初始化为空
            add.setMessageId("");
            this.baseMapper.insert(add);
        }else {
            ChatList update = new ChatList();
            update.setId(one.getId());
            update.setUpdateTime(new Date());
            this.baseMapper.updateById(update);
        }
        return ResultMap.ok().toString();
    }
}
